package com.guo.entity.service.impl;

import com.guo.config.AjaxResult;
import com.guo.entity.User;
import com.guo.entity.service.IUserService;
import com.guo.mapper.UserMapper;
import com.guo.utils.MD5Utils;
import com.guo.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> queryAll() {
        return userMapper.queryAll();
    }

    @Override
    public AjaxResult login(User user) {
        //加盐加密 uuid+admin+alibaba
        String pwd = MD5Utils.encrypByMd5(/*MyUtils.getUuid()+*/user.getPassword() + "alibaba");
        user.setPassword(pwd);  //密文设回去
        User u = userMapper.queryByUserName(user.getUsername());
        if (u!=null){
            //查到 比对密码
            if (user.getPassword().equals(u.getPassword())){
                //可以登录
                //生成一个token,保存到redis
                String token = MyUtils.getUuid();
                user.setPassword(""); // 为了安全，将密码置空
                redisTemplate.opsForValue().set(token,user);
                return AjaxResult.me();
            }
            else {
                return AjaxResult.me("用户名或密码错误!");
            }
        }else {
            return AjaxResult.me("用户名或密码错误!");
        }
    }

    @Override
    public AjaxResult register(User user) {
        if(userMapper.queryByUserName(user.getUsername())!=null){
            return AjaxResult.me("用户名已存在!");
        }else {
            //加盐加密 uuid+admin+alibaba
            String pwd = MD5Utils.encrypByMd5(/*MyUtils.getUuid()+*/user.getPassword() + "alibaba");
            user.setPassword(pwd);  //密文设回去
            return AjaxResult.me(userMapper.insertUser(user));
        }
    }
}
